package com.it.schoolhomeos.controller;

import com.it.schoolhomeos.entity.User;
import com.it.schoolhomeos.enums.Role;
import com.it.schoolhomeos.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/admin")
@PreAuthorize("hasRole('ADMIN')")
@Tag(name = "管理员管理", description = "提供管理员用户的管理功能")
public class AdminController {

    @Autowired
    private UserService userService;

    @GetMapping("/admins/init")
    @Operation(summary = "初始化测试数据", description = "创建一个测试管理员用户")
    public ResponseEntity<Map<String, Object>> initTestData() {
        try {
            // 检查是否已存在
            if (userService.existsByUsername("admin2")) {
                return ResponseEntity.ok(Map.of(
                    "status", "success",
                    "message", "测试管理员用户已存在",
                    "username", "admin2",
                    "password", "123456"
                ));
            }
            
            // 创建测试管理员用户
            User admin = new User();
            admin.setUsername("admin2");
            admin.setPassword("123456"); // 会在service中加密
            admin.setName("测试管理员");
            admin.setPhone("13800138003");
            admin.setEmail("admin2@example.com");
            admin.setRole(Role.ADMIN);
            admin.setEnabled(true);
            admin.setCreateTime(LocalDateTime.now());
            admin.setUpdateTime(LocalDateTime.now());
            
            User savedAdmin = userService.createAdmin(admin);
            
            Map<String, Object> result = new HashMap<>();
            result.put("status", "success");
            result.put("message", "测试管理员用户创建成功");
            result.put("username", savedAdmin.getUsername());
            result.put("password", "123456"); // 原始密码
            result.put("id", savedAdmin.getId());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.ok(Map.of(
                "status", "error",
                "message", "创建测试管理员用户失败: " + e.getMessage()
            ));
        }
    }

    @GetMapping("/admins")
    @Operation(summary = "获取管理员列表", description = "分页获取所有管理员用户")
    public ResponseEntity<Page<User>> getAdmins(
            @Parameter(description = "页码") @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") int size,
            @Parameter(description = "搜索关键词") @RequestParam(required = false) String keyword) {
        return ResponseEntity.ok(userService.findAdmins(page, size, keyword));
    }

    @GetMapping("/admins/{id}")
    @Operation(summary = "获取管理员详情", description = "根据ID获取管理员用户详情")
    public ResponseEntity<User> getAdmin(@Parameter(description = "管理员ID") @PathVariable Long id) {
        return ResponseEntity.ok(userService.findAdminById(id));
    }

    @PostMapping("/admins")
    @Operation(summary = "创建管理员", description = "创建新的管理员用户")
    public ResponseEntity<User> createAdmin(@Parameter(description = "管理员信息") @RequestBody User user) {
        return ResponseEntity.ok(userService.createAdmin(user));
    }

    @PutMapping("/admins/{id}")
    @Operation(summary = "更新管理员", description = "更新管理员用户信息")
    public ResponseEntity<User> updateAdmin(
            @Parameter(description = "管理员ID") @PathVariable Long id,
            @Parameter(description = "管理员信息") @RequestBody User user) {
        user.setId(id);
        return ResponseEntity.ok(userService.updateAdmin(user));
    }

    @DeleteMapping("/admins/{id}")
    @Operation(summary = "删除管理员", description = "删除指定的管理员用户")
    public ResponseEntity<Void> deleteAdmin(@Parameter(description = "管理员ID") @PathVariable Long id) {
        userService.deleteAdmin(id);
        return ResponseEntity.ok().build();
    }
} 